#!/bin/bash

if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "bash bwa-0.7.17.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

[[ ! "$1" =~ ^/.* || ! -d "$1" || "$1" = "/" ]] &&  echo "请输入正确的构建路径" && exit 1
[[ ! "$2" =~ ^/.* || ! -d "$2" || "$2" = "/" ]] &&  echo "请输入正确的安装路径" && exit 1

buildpath=$1
installpath=$2
[[ "$buildpath" =~ .*/$ ]] && buildpath=${buildpath%/*}
[[ "$installpath" =~ .*/$ ]] && installpath=${installpath%/*}
[[ "$buildpath" == "$installpath" ]] && echo "构建路径与安装路径需为不同路径" && exit 1

yum install -y environment-modules patch libatomic autoconf automake libtool numactl binutils systemd-devel valgrind flex wget
set -e

wget -t 10 -c -P $buildpath https://sourceforge.net/projects/bio-bwa/files/bwa-0.7.17.tar.bz2
tar -xvf $buildpath/bwa-0.7.17.tar.bz2 -C $buildpath && rm -rf $buildpath/bwa-0.7.17.tar.bz2
cd $buildpath/bwa-0.7.17
ln -fs /usr/lib64/libz.so.1.2.11 /usr/lib64/libz.so
git clone https://github.com/jratcliff63367/sse2neon.git
cp ./sse2neon/SSE2NEON.h $installpath/bisheng-compiler-2.1.0/lib/clang/12.0.0/include
sed -i -e 's/gcc/clang/g' \
    -i -e 's#INCLUDES=#INCLUDES= -I/\$$installpath/bisheng-compiler-2.1.0/lib/clang/12.0.0/include/#g' Makefile
sed -i -e 's/#include <emmintrin.h>/#include <SSE2NEON.h>/g' ksw.c
sed  -i -e '33d' rle.h
CFLAGS="-march=armv8.2-a -ffp-contract=off -fsigned-char"
make -j$(nproc)

mkdir -p $installpath/bwa-0.7.17 && cp -r $buildpath/bwa-0.7.17/* $installpath/bwa-0.7.17
cat>"$installpath/bwa-0.7.17/bwa_modulefiles"<<EOF
#%Module1.0
conflict bwa
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
    set modfile_path [file dirname \$modfile]
    return \$modfile_path
}
set pwd [getModulefileDir]
set BWA \$pwd
setenv BWA \$BWA
prepend-path PATH \$BWA
EOF

rm -rf $buildpath/bwa-0.7.17
